package ans.base;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;


/**
 * @Author wujie
 * @Class ArgGen
 * @Description
 * @Date 2021/4/21 10:58
 */
public class ArgGen {

    private static <T> T getFromJson(String str, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            T target = objectMapper.readValue(str, clazz);
            return target;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static TreeNode getTree(String data) {
        if (data.equals("[]")) return null;
        String[] strings = data.substring(1, data.length() - 1).split(",");
        TreeNode root = new TreeNode(Integer.parseInt(strings[0]));
        Queue<TreeNode> queue = new LinkedList<TreeNode>() {{
            add(root);
        }};
        int i = 1;
        while (!queue.isEmpty() && i < strings.length) {
            TreeNode node = queue.poll();
            if (!strings[i].equals("null")) {
                node.left = new TreeNode(Integer.parseInt(strings[i]));
                queue.add(node.left);
            }
            i++;
            if (i >= strings.length) {
                break;
            }
            if (!strings[i].equals("null")) {
                node.right = new TreeNode(Integer.parseInt(strings[i]));
                queue.add(node.right);
            }
            i++;
        }
        return root;


    }

    /**
     * 不生产环形链表
     *
     * @param str
     * @return
     */
    public static ListNode getLinkList(String str) {
        List<Integer> fromJson = getFromJson(str, List.class);
        ListNode root = null;
        if (!fromJson.isEmpty()) {
            root = new ListNode(fromJson.get(0));
        }
        ListNode temp = root;
        for (int i = 1; i < fromJson.size(); i++) {
            ListNode t = new ListNode(fromJson.get(i));
            temp.next = t;
            temp = t;
        }

        return root;
    }

    public static <T> Object gen(String str, Class<T> clazz) {
        if (clazz.equals(TreeNode.class)) {
            return getTree(str);
        } else if (clazz.equals(ListNode.class)) {
            return getLinkList(str);
        } else {
            return getFromJson(str, clazz);
        }
    }
}
